<template>
  <div class="app-container">
    <el-card>
      <!-- 标题 -->
      <div slot="header" class="clearfix">
        <span>学业导师与辅导员管理</span>
      </div>

      <!-- 查询区 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" @submit.prevent="fetchData">
          <el-form-item label="导师姓名">
            <el-autocomplete
              v-model="searchForm.teacherName"
              :fetch-suggestions="queryTeacherForSearch"
              placeholder="请输入导师姓名"
              @select="handleTeacherSelectForSearch"
            >
              <template #default="{ item }">
                <div class="autocomplete-item">{{ item.label }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
          <el-button type="success" @click="openAddDialog">新增</el-button>
        </el-form>
      </div>

      <!-- 表格展示 -->
      <div class="table-container">
        <el-table :data="tutorClassList" border style="width: 100%">
          <el-table-column prop="teacherName" label="导师姓名" align="center" />
          <el-table-column prop="className" label="班级名称" align="center" />

          <!-- 操作 -->
          <el-table-column label="操作" align="center" width="150">
            <template #default="scope">
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 新增弹窗 -->
      <el-dialog
        title="新增导师-班级绑定"
        :visible.sync="addDialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <el-form
          ref="addForm"
          :model="newTutorClass"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="导师姓名" prop="teacherName">
            <el-autocomplete
              v-model="newTutorClass.teacherName"
              :fetch-suggestions="queryTeacher"
              placeholder="请输入导师姓名"
              @select="handleTeacherSelect"
            >
              <template #default="{ item }">
                <div class="autocomplete-item">{{ item.label }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>

          <el-form-item label="班级名称" prop="className">
            <el-autocomplete
              v-model="newTutorClass.className"
              :fetch-suggestions="queryClass"
              placeholder="请输入班级名称"
              @select="handleClassSelect"
            >
              <template #default="{ item }">
                <div class="autocomplete-item">{{ item.label }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>

          <el-button type="primary" @click="submitAdd">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getAllTutorClasses,
  getTutorByTeacherId,
  addTutorClass,
  deleteTutorClass
} from '@/api/tutor'

export default {
  name: 'TutorClassManagement',
  data() {
    return {
      // 查询条件
      searchForm: {
        teacherName: '' // 原来是 teacherId
      },
      // 数据列表
      tutorClassList: [],
      // 导师与班级的映射关系
      tutorMap: new Map([
        ['鲁云平', '990000940715'],
        ['王家伟', '990000950723'],
        ['何伟', '990201300015'],
        ['李益才', '990000920731']
      ]),
      classMap: new Map([
        ['计科（二学位）2401班', 'class192'],
        ['计科（全英文）2401班', 'class196'],
        ['计科2202班', 'class205'],
        ['计科2203班', 'class208'],
        ['计科2204班', 'class207']
      ]
      ),

      // 新增表单
      addDialogVisible: false,
      newTutorClass: {
        teacherId: '',
        classId: '',
        teacherName: '', // 使用导师姓名
        className: '' // 使用班级名称
      },
      loading: false,

      // 表单验证规则
      rules: {
        teacherName: [
          { required: true, message: '导师姓名不能为空', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '班级名称不能为空', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    // 修改 fetchData 方法
    async fetchData() {
      this.loading = true
      try {
        const teacherId = this.tutorMap.get(this.searchForm.teacherName)
        const response = teacherId
          ? await getTutorByTeacherId(teacherId)
          : await getAllTutorClasses()

        if (response.success) {
          this.tutorClassList = response.data
        } else {
          this.$message.error(response.message)
        }
      } catch (error) {
        this.$message.error('数据加载失败')
      } finally {
        this.loading = false
      }
    },
    // 打开新增弹窗
    openAddDialog() {
      this.addDialogVisible = true
      this.newTutorClass = {
        teacherId: '',
        classId: ''
      }
    },
    // 班级搜索
    queryClass(queryString, cb) {
      const results = Array.from(this.classMap.keys())
        .filter(name => name.includes(queryString))
        .map(name => ({ label: name, value: name }))
      cb(results)
    },
    // 班级选择回调
    handleClassSelect(item) {
      this.newTutorClass.className = item.value
    },
    // 导师搜索（用于查询）
    queryTeacherForSearch(queryString, cb) {
      const results = Array.from(this.tutorMap.keys()).filter(name => name.includes(queryString))
        .map(name => ({ label: name, value: name }))
      cb(results)
    },
    // 导师选择回调（用于查询）
    handleTeacherSelectForSearch(item) {
      this.searchForm.teacherName = item.value
    },
    // 导师搜索
    queryTeacher(queryString, cb) {
      const results = Array.from(this.tutorMap.keys()).filter(name => name.includes(queryString))
        .map(name => ({ label: name, value: name }))
      cb(results)
    },
    // 导师选择回调
    handleTeacherSelect(item) {
      this.newTutorClass.teacherName = item.value
    },

    // 提交新增
    async submitAdd() {
      const valid = await this.$refs.addForm.validate()
      if (!valid) return

      try {
        const teacherId = this.tutorMap.get(this.newTutorClass.teacherName)
        const classId = this.classMap.get(this.newTutorClass.className)

        if (!teacherId || !classId) {
          this.$message.error('导师或班级名称无效')
          return
        }

        const result = await addTutorClass(teacherId, classId) // 改动点

        if (result.success) {
          this.$message.success('新增成功')
          this.addDialogVisible = false
          this.fetchData()
        } else {
          this.$message.error(result.message || '新增失败')
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    // 删除记录
    async handleDelete(row) {
      try {
        const result = await this.$confirm(
          `确定要删除 ${row.teacherId} 和 ${row.classId} 的绑定吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        if (result === 'confirm') {
          const res = await deleteTutorClass(row.teacherId, row.classId)
          if (res.success) {
            this.$message.success('删除成功')
            this.fetchData()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        }
      } catch {
        // 取消操作
      }
    },
    // 表单重置
    resetForm() {
      this.newTutorClass = {
        teacherId: '',
        classId: ''
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
}

.autocomplete-item {
  padding: 10px;
  cursor: pointer;
  &:hover {
    background-color: #f5f7fa;
  }
}
</style>
